#include <assert.h>
#include "gfxutil.h"
#include "mesh.h"
#include "meshgen.h"
#include "texture.h"
#include "shader.h"
#include "sdrman.h"
#include "opengl.h"
#include "logger.h"

using namespace goatgfx;

void goatgfx::draw_rect(const Vector3 &v1, const Vector3 &v2, Texture *tex, ShaderProg *sdr)
{
	static ShaderProg *defsdr;

	if(!defsdr) {
		if(!(defsdr = get_sdrprog("defpost.v.glsl", "defpost.p.glsl"))) {
			static bool didlog;
			if(!didlog) {
				error_log("draw_rect: failed to load default shader\n");
				didlog = true;
			}
			if(!sdr) {
				return;
			}
		}
	}


	if(tex) {
		bind_texture(tex);
	}
	if(sdr) {
		sdr->bind();
	} else {
		defsdr->bind();

		assert(defsdr->get_attrib_location("attr_vertex") == MESH_ATTR_VERTEX);
		assert(defsdr->get_attrib_location("attr_texcoord") == MESH_ATTR_TEXCOORD);
	}


	float varr[] = {
		v1.x, v1.y, v1.z, v2.x, v1.y, v2.z,
		v2.x, v2.y, v2.z, v1.x, v2.y, v1.z
	};
	static const float tarr[] = { 0, 0, 1, 0, 1, 1, 0, 1 };
	static const unsigned int idxarr[] = {0, 1, 2, 0, 2, 3};

	// disable VBOs if they are enabled
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	glEnableVertexAttribArray(MESH_ATTR_VERTEX);
	glVertexAttribPointer(MESH_ATTR_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, varr);
	glEnableVertexAttribArray(MESH_ATTR_TEXCOORD);
	glVertexAttribPointer(MESH_ATTR_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, tarr);

	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, idxarr);

	glDisableVertexAttribArray(MESH_ATTR_VERTEX);
	glDisableVertexAttribArray(MESH_ATTR_TEXCOORD);

	bind_texture(0);
}
